const axios = require('axios');
const db = uniCloud.database();
const dbCmd = db.command;
const pubAcc = require('../Config.js')

async function getticket() {
  let ticketObj = await getTicketDb()
  // let ticketObj = null
  if (ticketObj) {
    return ticketObj
  } else {
    let dbResult = await getTokenApi().then(tokenObj => {
      console.log("getticket=====1111111", tokenObj)
      return getTicketApi(tokenObj.access_token)
    }).then(ticketRes => {
      return saveTicketDb(ticketRes)
    }).then(saveTicket => {
      console.log("Save-db-result " + JSON.stringify(saveTicket))
      return db.collection("uni-verify").doc(saveTicket.id).get()
    }).catch(error => {
      console.error("getticket-error===========" + error)
    })

    console.log("Request-result " + JSON.stringify(dbResult))
    let ticketData = dbResult.data[0].ticket
    return ticketData
  }
}

async function getTicketApi(token) {
  let ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&" + `access_token=${token}`
  let ticket_obj = await getWebData(ticket_url, "ticket")
  ticket_obj.token = token
  return ticket_obj
}

async function getTokenApi() {
  console.log("getTokenApi" + JSON.stringify(pubAcc))
  let token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
      `&appid=${pubAcc.appid}&secret=${pubAcc.secret}`
  // let token_url = "https://zhaoyj.work/express/demo/getTokenApi" +
  // 	`?appid=${pubAcc.appid}&secret=${pubAcc.secret}`
  return getWebData(token_url, "token")
}

async function getTicketDb() {
  let ticketObj = ''
  // 1.查看state为0的wxTicket数据
  let ticketList = await db.collection("uni-verify").where({
    flag: "wxTicket",
    state: 0
  }).get()
  console.log("verifyDb " + JSON.stringify(ticketList))
  ticketList = ticketList.data
  let timestamp = Date.parse(new Date());
  if (ticketList && ticketList.length > 0) {
    ticketObj = ticketList[0]
    // 2.如果存在state为0的wxTicket数据；并且时间未过期：则返回该ticket数据
    if (ticketObj.expired_at - timestamp > 2000) {
      // if (ticketObj.expired_at - timestamp > 7200 * 1000) { //测试
      return ticketObj.ticket
    } else {
      // 3.如果存在state为0的wxTicket数据；时间已过期：则修改该wxTicket数据的state状态，并返回空
      console.log("verifyDb-update======== " + JSON.stringify(ticketObj))
      let res = updateTicketDb(ticketObj)
      return ""
    }
  } else {
    return ""
  }
}

async function saveTicketDb(ticket) {
  let token = ticket.token
  let created_at = Date.parse(new Date());
  let expired_at = created_at + 7200 * 1000
  let result = await db.collection("uni-verify").add({
    created_at,
    expired_at,
    state: 0,
    token,
    ticket: ticket,
    flag: "wxTicket"
  })
  return result
}

async function updateTicketDb(ticketObj) {
  let result = await db.collection("uni-verify").doc(ticketObj._id).set({
    state: 1
  })
  return result
}

async function getWebData(web_url, flag) {
  let log1 = "WebData-request====" + flag
  let log2 = "WebData-request====" + flag
  return new Promise((resolve, reject) => {
    axios(web_url).then(html => {
      console.log(log1, web_url)
      console.log(log2, html)
      let {data} = html
      resolve(data);
    }).catch(err => {
      reject(err);
    })
  })
}

module.exports = getticket;
